import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/stores/user";
import { useRouter } from "vue-router";
const router = useRouter()
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 10000
})
//拦截器
// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    //携带token
    const userStore = useUserStore()
    const token = userStore.userinfo.token
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
    ElMessage({ type: 'warning', message: e.response.data.message })
    //处理401状态
    if (e.response.status === 401) {
        const userStore = useUserStore()
        userStore.cleanUserinfo()
        router.push('login')
    }
    return Promise.reject(e)
})
export default httpInstance